package com.ting.test.algorithms.查找算法.归并查找;

/**
 * 给定一个数组arr，两个整数lower和upper，
 * <p>
 * 返回arr中有多少个子数组的累加和在[lower,upper]范围上
 */
public class 归并排序补充问题暴力解 {
    public static void main(String[] args) {
        int[] arr = new int[]{3, 4, 6, 7, 8, 9, 4, 2, 1, 7, 9,43,6,7,8,9,0,2,3,5,7,8,0,7};
        int L = 3;
        int R = 6;
        int result1 = count1(arr, L, R);
        int result2 = count2(arr, L, R);
        System.out.println(result1);
        System.out.println(result2);
    }

    public static int count1(int[] arr, int L, int R) {
        if (arr == null) {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                int sum = 0;
                for (int m = i; m <= j; m++) {
                    sum += arr[m];
                }
                if (sum >= L && sum <= R) {
                    count++;
                }
            }
        }
        return count;
    }

    public static int count2(int[] arr, int L, int R) {
        if (arr == null) {
            return 0;
        }
        int[] sum = new int[arr.length];
        sum[0] = arr[0];
        for (int i = 1; i < arr.length; i++) {
            sum[i] = sum[i - 1] + arr[i];
        }

        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                int sumTemp = 0;
                if (i == 0) {
                    sumTemp = sum[j];
                } else {
                    sumTemp = sum[j] - sum[i - 1];
                }
                if (sumTemp >= L && sumTemp <= R) {
                    count++;
                }
            }
        }
        return count;
    }
}
